package com.hs.sentinelr.componet;

import com.hs.sentinelr.anno.AccessLimit;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * 限流拦截器
 *
 * @Author lingNan
 * @Date 2021/8/22 9:42 下午
 **/
@Component
public class AccessLimitIntercepter implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
            if (null == accessLimit) {
                return true;
            }
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            int seconds = accessLimit.seconds();
            if (needLogin) {
                // TODO: 2021/8/22 判断是否登录
            }
            //获取http://ip:8080
            String ip = request.getRemoteAddr();
            String key = ip + request.getServletPath();

            Integer count = (Integer) redisUtil.getKey(key);
            //首次进入
            if (null == count || -1 == count) {
                redisUtil.set(key, 1, seconds, TimeUnit.SECONDS);
                return true;
            }
            //访问次数小于最大次数，则加1
            if (count < maxCount) {
                redisUtil.incr(key, 1);
                return true;
            } else {
                response.setContentType("text/plain; charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().print(seconds + "秒内访问不能超过" + count + "次");
                return false;
            }
        }
        return true;
    }
}
